//
//  SegmentView.m
//  homeland
//
//  Created by rain on 14-5-22.
//  Copyright (c) 2014年 xzysun. All rights reserved.
//

#import "SegmentView.h"
@interface SegmentView()
@property (nonatomic ,strong) NSMutableArray *btns;
@end;
@implementation SegmentView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)initView:(NSArray *)array
{
    self.btns = [[NSMutableArray alloc] init];
    int width = self.frame.size.width / array.count;
    for (int i = 0; i < array.count; i++) {
        

        NSDictionary *dict = array[i];
        
        NSLog(@"dict = %@",dict[@"image"]);
        NSLog(@"dict = %@",dict[@"light"]);

        UIImage *image = [UIImage imageNamed:dict[@"image"]];
        UIImage *light = [UIImage imageNamed:dict[@"light"]];

        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(width * i, 0, image.size.width / 2, image.size.height / 2)];
        if (array.count == 1) {
            [button setCenter:CGPointMake(160, 18)];
        }
        [button setImage:image forState:0];
        [button setImage:light forState:4];
        button.tag = i;
        [button addTarget:self action:@selector(selectSegment:) forControlEvents:64];
        [self.btns addObject:button];
        [self addSubview:button];
        button.selected = i == 0? YES : NO;
        
    }
}

- (void)selectSegment:(UIButton *)button
{
    for (UIButton *btn in self.btns) {
        btn.selected = NO;
    }
    button.selected = YES;
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(didSelectSegmentAtIndex:)]) {
        self.segmentIndex = button.tag;
        [self.delegate didSelectSegmentAtIndex:button.tag];
    }
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
